package com.rabbitmq.demos.work;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.utils.ConnectionUtil;
import com.rabbitmq.utils.RabbitConfig;

public class Consumer2 {
    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel =connection.createChannel();
        channel.queueDeclare(RabbitConfig.queue, true, false, false, null);
        System.out.println(" [X2*] Waiting for messages. To exit press CTRL+C");
        // 同一时刻服务器只会发一条消息给消费者
        channel.basicQos(1);

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");

            System.out.println(" [x2] Received '" + message + "'");
            System.out.println(delivery);
            System.out.println(delivery.getEnvelope().getDeliveryTag());
            try {
                doWork(message);
            } finally {
                System.out.println(" [x2] Done");
                //开启这行 表示使用手动确认模式  ，使用公平分发,必须关闭自动应答，改为手动应答。
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        };
        // 监听队列，false表示手动返回完成状态，true表示自动
        channel.basicConsume(RabbitConfig.queue, false, deliverCallback, consumerTag -> { });
    }

    private static void doWork(String task) {
        for (char ch : task.toCharArray()) {
            if (ch == '.') {
                try {
                    //根据不同的睡眠时间  体现出能力  实现能者多劳的Work模式  （两个消费者能力一样 就相当于轮询了）
                    Thread.sleep(1000);
                } catch (InterruptedException _ignored) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }
}
